﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Learn_delegateUse
{
    class Program
    {
        static void Main(string[] args)
        {
            // 模板方法，“借用”指定的外部方法来产生结果
            // 回调（callback）方法，调用指定的外部方法 
            // 用委托类型的参数封装一个外部的方法，然后再把这个外部的方法传入方法的内部进行间接调用
            ProductFactory productFactory = new ProductFactory();
            WrapFactory wrapFactory = new WrapFactory();

            Func<Product> func1 = new Func<Product>(productFactory.MakePizza);
            Func<Product> func2 = new Func<Product>(productFactory.MakeToyCar);

            Logger logger = new Logger();
            Action<Product> log = new Action<Product>(logger.Log);

            Box box1 = wrapFactory.WrapProduct(func1, log);
            Box box2 = wrapFactory.WrapProduct(func2, log);

            Console.WriteLine(box1.Product.Name);
            Console.WriteLine(box2.Product.Name);

        }
    }

    class Logger
    {
        public void Log(Product product)
        {
            Console.WriteLine("Product {0} created at {1}. Price is {2}.", product.Name, DateTime.UtcNow, product.Price);
        }
    }

    class Product
    {
        public string Name { get; set; }  // 这段语句C#会默认生成一个 private string Name; 的属性
        // get {return Name;}
        // set {Name = value;}
        // get 和 set主要用于访问和修改private字段，给外部提供一个能够访问到private的方法

        public double Price { get; set; }
    }

    class Box
    {
        public Product Product { get; set; }
    }

    class WrapFactory
    {
        public Box WrapProduct(Func<Product> getProduct, Action<Product> logCallBack)
        {
            Box box = new Box();
            Product product = getProduct.Invoke();
            if(product.Price >= 50)
            {
                logCallBack.Invoke(product);
            }

            box.Product = product;
            return box;
        }
    }

    class ProductFactory
    {
        public Product MakePizza()
        {
            Product product = new Product();
            product.Name = "Pizza";
            product.Price = 12;
            return product;
        }

        public Product MakeToyCar()
        {
            Product product = new Product();
            product.Name = "Toy Car";
            product.Price = 70;
            return product;
        }
    }
}
